package me.zxk.smartagriculture.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zxk.smartagriculture.common.ErrorCode;
import me.zxk.smartagriculture.dto.auth.LoginRequest;
import me.zxk.smartagriculture.dto.auth.LoginResponse;
import me.zxk.smartagriculture.dto.auth.RegisterRequest;
import me.zxk.smartagriculture.entity.User;
import me.zxk.smartagriculture.entity.UserSettings;
import me.zxk.smartagriculture.repository.UserRepository;
import me.zxk.smartagriculture.repository.UserSettingsRepository;
import me.zxk.smartagriculture.util.JwtUtil;
import me.zxk.smartagriculture.util.PasswordUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 认证服务
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AuthService {

    private final UserRepository userRepository;
    private final UserSettingsRepository userSettingsRepository;
    private final JwtUtil jwtUtil;

    /**
     * 用户注册
     */
    @Transactional
    public Long register(RegisterRequest request) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(request.getUsername())) {
            throw new RuntimeException(ErrorCode.USERNAME_EXISTS.getMessage());
        }

        // 创建用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPasswordMd5(PasswordUtil.encode(request.getPasswordMd5()));
        user.setNickname("智农用户");

        User savedUser = userRepository.save(user);

        // 创建默认用户设置
        UserSettings userSettings = new UserSettings();
        userSettings.setUserId(savedUser.getId());
        userSettings.setDarkModeEnabled(false);
        userSettings.setNotificationsEnabled(true);
        userSettingsRepository.save(userSettings);

        log.info("用户注册成功: {}", request.getUsername());
        return savedUser.getId();
    }

    /**
     * 用户登录
     */
    public LoginResponse login(LoginRequest request) {
        // 查找用户
        User user = userRepository.findByUsername(request.getUsername())
                .orElseThrow(() -> new RuntimeException(ErrorCode.LOGIN_FAILED.getMessage()));

        // 验证密码
        if (!PasswordUtil.matches(request.getPasswordMd5(), user.getPasswordMd5())) {
            throw new RuntimeException(ErrorCode.LOGIN_FAILED.getMessage());
        }

        // 生成JWT Token
        String token = jwtUtil.generateToken(user.getUsername(), user.getId());

        log.info("用户登录成功: {}", request.getUsername());
        return new LoginResponse(token, user.getId(), user.getUsername(), user.getNickname());
    }
}
